package com.ydx.aa76111.agent.runtime;

import org.jacoco.core.internal.data.CRC64;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

class ClassFileDumper {
    private final File location;

    ClassFileDumper(String location) {
        if (location == null) {
            this.location = null;
        } else {
            this.location = new File(location);
        }

    }

    void dump(String name, byte[] contents) throws IOException {
        if (this.location != null) {
            int pkgpos = name.lastIndexOf(47);
            File outputdir;
            String localname;
            if (pkgpos != -1) {
                outputdir = new File(this.location, name.substring(0, pkgpos));
                localname = name.substring(pkgpos + 1);
            } else {
                outputdir = this.location;
                localname = name;
            }

            outputdir.mkdirs();
            Long id = CRC64.classId(contents);
            File file = new File(outputdir, String.format("%s.%016x.class", localname, id));
            OutputStream out = new FileOutputStream(file);
            out.write(contents);
            out.close();
        }

    }
}